// pages/collection/collection.js
let app = getApp()
import req from '../../utils/req';
import utils from '../../utils/utils';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //用户列表
    users: [],
    managementIds: [], //要推送的商品id
    selectUsers: [], //选中用户
    pageSize: 10, //分页，默认为10
    startX: 0, //开始坐标
    startY: 0,
    page: 1,
    history: [],
    searchValue: '',
    totalhistory: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.search('search')
  },

  search(type) {
    type === 'search' ? this.setData({
      history: []
    }) : type === 'refrash' ? wx.showNavigationBarLoading() : '' //刷新加载
    const data = {
      page: this.data.page,
      uid: app.globalData.userInfo.uid
    }
    this.data.searchValue !== '' ? data['taps'] = this.data.searchValue : ''
    req.get('加载中', '/moment/selectUserHistory', data, (res) => {
      const data = res.data
      data.list.forEach(e1 => {
        const images = []
        let taps = e1['taps'].split(',')
        e1['images'].forEach(e2 => {
          images.push(e2.url)
        })
        e1.images = images
        e1.taps = taps
        e1['createTime'] = utils.timeFormat(e1['createTime'])
      });
      this.setData({
        totalhistory: data.total,
        history: this.data.history.concat(data.list)
      })
      if (type === 'refrash') {
        wx.hideNavigationBarLoading(); //完成停止加载图标
        wx.stopPullDownRefresh();
        utils.toast('success', '刷新成功', 500)
      }
    })
  },


  //获取关注列表
  getMyClerk: function (searchKey) {},

  //获取搜索框内容
  inputTyping: function (e) {
    this.setData({
      searchValue: e.detail.value
    })
    if (this.data.searchValue === '') {
      this.search('search')
    }
  },
  //搜索
  handleSearch: function () {
    this.search('search')
  },

  deleteHistory(e) {
    const data = {
      sid: e.currentTarget.dataset.sid,
      uid: app.globalData.userInfo.uid
    }
    req.post('', '/user/deleteHistory', data, (res) => {
      if (res.status === 200) {
        utils.toast('success', res.msg, 1000)
        this.search("search")
      }
    })
  },

  navToDetail(e) {
    let url = '../detail/detail?sid=' + e.currentTarget.dataset.sid
    wx.navigateTo({
      url
    })
  },


  touchE: function (e) {
    // console.log(e);
    var that = this
    try {
      if (e.changedTouches.length == 1) {
        //手指移动结束后触摸点位置的X坐标
        var endX = e.changedTouches[0].clientX;
        //触摸开始与结束，手指移动的距离
        var disX = that.data.startX - endX;
        var delBtnWidth = that.data.delBtnWidth;
        //如果距离小于删除按钮的1/2，不显示删除按钮
        var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx";

        //获取手指触摸的是哪一项
        var index = e.currentTarget.dataset.index;
        var list = that.data.history;
        list[index].txtStyle = txtStyle;
        //更新列表的状态
        that.setData({
          history: list
        });
      }
    } catch (error) {}
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    // console.log(e)
    //开始触摸时 重置所有删除
    this.data.history.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      history: this.data.history
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.history.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      history: that.data.history
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let pages = getCurrentPages(); //页面栈
    let beforePage = pages[pages.length - 2];
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      history: []
    })
    this.search("refrash")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const length = this.data.users.length
    const total = this.data.totalhistory
    let page = this.data.page
    if (length < total) {
      page += 1;
      this.setData({
        page
      })
      this.search()
    } else {
      utils.toast("到底啦")
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})